package com.comall.dc.banktest.domain;

import com.comall.dc.banktest.domain.exception.AccountFreezeException;
import com.comall.dc.banktest.domain.exception.AccountNoAuthException;
import com.comall.dc.banktest.domain.exception.AccountNotExistException;
import com.comall.dc.banktest.domain.exception.BalanceInsufficientException;
import com.comall.dc.banktest.domain.model.Account;
import com.comall.dc.banktest.domain.model.AccountRecord;
import com.comall.dc.banktest.domain.repository.AccountRecordRepository;
import com.comall.dc.banktest.domain.repository.AccountRepository;
import com.comall.dc.banktest.infrastructure.core.BalanceOperationEnum;
import com.comall.dc.banktest.infrastructure.dao.service.AccountDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class AccountDomainService {

    @Autowired
    private AccountDAO accountService;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private AccountRecordRepository accountRecordRepository;

    public Account transferBalance(Integer sourceAccountId, Integer targetAccountId, String password, BigDecimal value) throws AccountFreezeException, AccountNotExistException, AccountNoAuthException, BalanceInsufficientException {

        Account account = accountRepository.load(sourceAccountId);
        if (!account.isAuthPass(password)){
            throw new AccountNoAuthException();
        }

        if (account.isFrozen()){
            throw new AccountFreezeException();
        }

        Account targetAccount = accountRepository.load(targetAccountId);
        account = accountRepository.save(account);
        accountRepository.save(targetAccount);
        AccountRecord accountRecord = new AccountRecord(BalanceOperationEnum.TRANSFER, sourceAccountId, targetAccountId, value);
        accountRecordRepository.save(accountRecord);

        return account;

    }

    public boolean isIdCardExist(String idCard){
        return accountService.isIdCardExist(idCard);
    }


}
